package com.ssau.expert.core.util;

import com.ssau.expert.core.model.Condition;
import com.ssau.expert.core.model.Operation;
import com.ssau.expert.core.model.Variable;

/**
 * Author: Sergey Saiyan
 * Created: 19.09.13 15:21
 */
public class ConditionHelper {

    public static boolean isTrue(Condition condition) {
        Variable var = condition.getVariable();
        if (var == null) {
            throw new RuntimeException("Can't check condition on null variable");
        }

        String varValue = var.getValue();
        String conditionValue = condition.getConditionValue();

        if (String.class.equals(var.getClazz())) {
            conditionValue = conditionValue.substring(1, conditionValue.length() - 1);
        }

        Operation op = condition.getOperation();
        Class clazz = var.getClazz();

        switch (op) {
            case EQUAL:
                return varValue.equals(conditionValue);
            case NOT_EQUAL:
                return !varValue.equals(conditionValue);
            case LESS:
                return checkLess(varValue, conditionValue, clazz);
            case MORE:
                return checkGreat(varValue, conditionValue, clazz);
            case LESS_EQUAL:
                return !checkGreat(varValue, conditionValue, clazz);
            case MORE_EQUAL:
                return !checkLess(varValue, conditionValue, clazz);
            default:
                throw new RuntimeException("Can't use ASSIGN in condition operations");
        }
    }

    private static boolean checkLess(String varValue, String conditionValue, Class clazz) {
        if (Integer.class.equals(clazz)) {
            int vv = Integer.valueOf(varValue);
            int cv = Integer.valueOf(conditionValue);
            return vv < cv;
        } else {
            throw new RuntimeException("Can't perform LESS condition check on class '" + clazz.getName() + "'");
        }
    }

    private static boolean checkGreat(String varValue, String conditionValue, Class clazz) {
        if (Integer.class.equals(clazz)) {
            int vv = Integer.valueOf(varValue);
            int cv = Integer.valueOf(conditionValue);
            return vv > cv;
        } else {
            throw new RuntimeException("Can't perform GREAT condition check on class '" + clazz.getName() + "'");
        }
    }
}
